/**
 * hnjz.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.hnjz.sys.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.hnjz.sys.role.Role;
import com.hnjz.sys.role.RoleMapper;

/**
 * 根据用户名得到用户信息
 * 
 * @author wumi
 * @version $Id: UserDetailsServiceImpl.java, v 0.1 Jan 6, 2013 5:21:55 PM wumi Exp $
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    /**日志*/
    private static final Log log = LogFactory.getLog(UserDetailsServiceImpl.class);

    @Autowired
    private UserMapper       userMapper;
    @Autowired
    private RoleMapper       roleMapper;

    /** 
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        //用户具有的角色
        User user = userMapper.findByLoginName(name);
        if (null == user) {
            throw new UsernameNotFoundException("用户： " + name + "不存在");
        }
        Role r = roleMapper.findRoleByUserId(user.getId());
        if(log.isDebugEnabled()){
            log.debug("用户："+user.getName()+"登录，角色："+r.getId());
        }
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(r.getId()));
        user.setRole(r.getId());
        user.setAuthorities(authorities);
        return user;
    }

}
